package com.ytzl.controller;

import cn.hutool.crypto.SecureUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ytzl.common.CodeResultEnums;
import com.ytzl.common.Constants;
import com.ytzl.common.R;
import com.ytzl.common.ResponseDataUtils;
import com.ytzl.config.RedisAPI;
import com.ytzl.modul.ItripUser;
import com.ytzl.service.ItripUserService;
import com.ytzl.service.TokenService;
import com.ytzl.utils.JwtUtils;
import com.ytzl.vo.TokenVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
@Slf4j
public class LoginController {

    @Resource
    private RedisAPI redisAPI;
    @Resource
    private ItripUserService userService;
    @Resource
    private TokenService tokenService;

    @ApiOperation("登录用户")
    @PostMapping("/login")
    public R userLogin(@RequestParam("userCode") String userCode,
                       @RequestParam("userPassword") String userPassword,
                       HttpServletRequest request){
        //1.校验入参是否为kong
        if (!StringUtils.isEmpty(userCode) && !StringUtils.isEmpty(userPassword)){
            //根据userCode和userPassword查询用户是否存在
            QueryWrapper wrapper=new QueryWrapper<>()
            .eq("userCode",userCode)
            .eq("userPassword",SecureUtil.md5(userPassword));
            ItripUser user=userService.getOne(wrapper);
            //3.判断用户是否存在
            if (user==null){
                return ResponseDataUtils.buildError(CodeResultEnums.USER_NOT_EXSITS);
            }
            //如果查到了，给该用户生成token，并且保存
            String token = tokenService.createToken(request.getHeader("user-agent"), user);
            tokenService.saveToken(token, user);
            //将token返回给客户端
            TokenVo tokenVo=new TokenVo(
                    token,
                    /*token的过期时间=生成token的时间+系统设置token过期时间*/
                    Calendar.getInstance().getTimeInMillis()+ Constants.SESSION_EXPIRE *1,
                    Calendar.getInstance().getTimeInMillis()
            );
            return ResponseDataUtils.buildSuccess(tokenVo);
        }else {
            //如果不存在，返回失败信息
            return ResponseDataUtils.buildError(CodeResultEnums.INPUT_PARAMS_IS_EMPTY);
        }

    }

    @PostMapping
    public Map<String,Object> login(@RequestBody ItripUser userForm){
        log.info("用户名：[{}]",userForm.getUsercode());
        log.info("密码：[{}]",userForm.getUserpassword());

        Map<String,Object> map=new HashMap<>();
        try {
            ItripUser userDB=this.findUserByCondition(userForm);
            Map<String,String> payload=new HashMap<>();
            payload.put("userId",userDB.getId().toString());
            payload.put("userName",userDB.getUsername());
            payload.put("userCode",userDB.getUsercode());
            //生成token令牌
            String token= JwtUtils.createToken(payload);

            log.info("userDB:[{}]",userDB);
            map.put("state",true);
            map.put("msg","登录成功");
            map.put("token",token);
        }catch (Exception e){
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }

    public ItripUser findUserByCondition(ItripUser user){
        QueryWrapper params=new QueryWrapper();
        params.eq("userCode",user.getUsercode());
        params.eq("Userpassword",SecureUtil.md5(user.getUserpassword()));
        return userService.getOne(params);
    }

    /*public Map<String,Object> test(String token){
        Map<String,Object>map=new HashMap<>();
        //一下内容放到拦截器中实现
        log.info("当前token：[{}]",token);
        try {
            DecodedJWT decodedJWT=JwtUtils.verifyToken(token);
            map.put("state",true);
            map.put("msg","请求成功");
            return map;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("msg","签名无效");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","token算法不一致");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","token无效");
        }
        map.put("state",false);
        return map;
    }*/

    public Map<String,Object> test(HttpServletRequest request){
        //此处做具体的业务逻辑
        Map<String,Object>map=new HashMap<>();
        String token=request.getHeader("token");
        DecodedJWT decodedJWT=JwtUtils.verifyToken(token);
        log.info("userId:[{}]",decodedJWT.getClaim("userId").asString());
        log.info("userName:[{}]",decodedJWT.getClaim("userName").asString());

        map.put("state",true);
        map.put("msg","请求成功");
        return map;
    }
}
